$(function (){
	  
	  
	 //组装请求参数数据
	 request_param();
	 //组装返回值参数
	 return_param();
	 //组装错误码参数
	 error_param();
	  
    //提交审核
    $("._api_add_submit").click(function (){
      var data = getApiData();
        data.api_charge_rules = getPackageData();
      data.api_auth_status=1;


        //console.log(data)

      if(!data){
    	  return;
      }
      
	  var cur = $(this);
	  // 按钮置为不可点击
	  it_enable(cur, true);
	  $('#register').attr("disabled",true);
	  $('#register_api').text('');
	  
		$('#register_api').waitMe({
			effect: 'ios',
			bg: 'rgba(16,128,242,0)',
			text: '提交中...',
			color:'#fff',
			padding:'10px',
			sizeW:'',
			sizeH:'',
			source: 'img.svg'
		});
	       
      
      $.ajax({
        url:'/apiworks/apiEdit.html',
        type:'POST',
        dataType:'json',
        async:true,
        data:data,
        success:function (req){
          it_enable(cur, false); 
		  $('#register').attr("disabled",false);
		  $('#register_api').waitMe('hide');
		  $('#register_api').text('提交审核');
          if(req.status==200){
        	show_msg({msg:req.msg,type:'ok',time:1000});
            location.href="/apiworks/apiList.html?service_id="+data.service_id+"&api_type=1";
          }else{
        	  if(req.status==1){
        		  add_auth_error(req.data,req.msg);
        	  }else{
        		  show_msg({msg:req.msg,type:'error'});
        	  }
          }
          return false;
        },
        error:function (){
          it_enable(cur, false); 
		  $('#register').attr("disabled",false);
		  $('#register_api').waitMe('hide');
		  $('#register_api').text('提交审核');
          show_msg({msg:'系统异常',type:'error',time:1000});
        }
      });

    });

    //临时保存
    $('._api_save').click(function (){
      var data = getApiData();
      data.api_auth_status = $(this).attr('data-authstatus');
      
      if(!data){
    	  return;
      }
  	  var cur = $(this);
	  // 按钮置为不可点击
	  $('#register').text('');
	  $('#register_api').attr("disabled", "true");

		$('#register').waitMe({
			effect: 'ios',
			bg: 'rgba(16,128,242,0)',
			text: '保存中...',
			color:'#fff',
			padding:'10px',
			sizeW:'',
			sizeH:'',
			source: 'img.svg'
		});
	  
      $.ajax({
        url:'/apiworks/apiEdit.html',
        type:'POST',
        dataType:'json',
        async:true,
        data:data,
        success:function (req){
          $('#register_api').attr("disabled",false);
		  $('#register').waitMe('hide');
		  $('#register').text('保存');
		  
          if(req.status==200){
        	  show_msg({msg:req.msg,type:'ok',time:1000});
          }else{
        	  if(req.status==1){
        		  add_auth_error(req.data,req.msg);
        	  }else{
        		  show_msg({msg:req.msg,type:'error'});
        	  }
          }
          return false;
        },
        error:function (){
          $('#register_api').attr("disabled",false);
		  $('#register').waitMe('hide');
		  $('#register').text('保存');
		  
          show_msg({msg:'系统异常',type:'error',time:1000});
        }
      });
    });


   $('#save').click(function(){
      //defining new user
      var user=Object();
      user['req_name']='';
      user['req_desc']='';
      user['req_default_value']='';
      user['req_type']='string';
      user['req_master']='1';
      user['req_master1']='selected';
      user['req_master2']='id';
      
      user['req_type1']='selected';
      user['req_type2']='id';
      user['req_type3']='id';
      jPut.users.append(user);
   });

    //on new user
   $('#save1').click(function(){
      //defining new user
      var user1=Object();
      user1['ret_name']='';
      user1['ret_desc']='';
      user1['ret_type']='string';
      user1['ret_type1']='selected';
      user1['ret_type2']='id';
      user1['ret_type3']='id';
      user1['ret_desc']='';
      
      jPut.users1.append(user1);
   });
 

   //on new user
   $('#save2').click(function(){
      //defining new user
      var user2=Object();
      user2['error_code']='';
      user2['error_info']='';
      user2["error_desc"]='';
      jPut.users2.append(user2);
   });

  });
  
function checkValue(obj,classname){
  var value = $(obj).val();//.attr('value');
  if(value!='' && !checkEnName(value)){
    $(obj).addClass('warning');
  }
  // //遍历所有子节点值
  $(classname).each(function (){
    if(this!=obj){
      var thisvalue = $(this).val();
      if(thisvalue==value){
        $(obj).addClass('warning');
        show_msg({type:'warning',msg:'值不能重复'});
        return false;
      }
    }
  });
}

function checkErrorCodeValue(obj,classname){
  var value = $(obj).val();//.attr('value');
  // //遍历所有子节点值
  $(classname).each(function (){
    if(this!=obj){
      var thisvalue = $(this).val();
      if(thisvalue==value){
        $(obj).addClass('warning');
        show_msg({type:'warning',msg:'值不能重复'});
        return false;
      }
    }
  });  
}

	function rmError(obj){
		$(obj).removeClass('warning');
	}
	
  //把请求参数写入页面
  function request_param(){
	  // var jsondata = <?php echo json_encode($info['api_request_param']); ?>;
    var jsondata = $('._hidden_api_request_param').val();
	  if(jsondata=='' || jsondata==null){
		  
		  var user=Object();
	      user['req_name']='';
	      user['req_desc']='';
	      user['req_default_value']='';
	      user['req_type']='string';
	      user['req_master']='1';
	      user['req_master1']='selected';
	      user['req_master2']='id';
	      
	      user['req_type1']='selected';
	      user['req_type2']='id';
	      user['req_type3']='id';
		  jPut.users.append(user);
		  return;
	  }
	  
	  var data = JSON.parse(jsondata);
	  for(var a in data){
	     var user=Object();
	     user['req_name']=data[a].name;
	     user['req_type']=data[a].type;
	     user['req_master']=data[a].mast;
	     user['req_desc']=data[a].desc;
	     user['req_default_value']=data[a].default_value;
	     
	     user['req_master1']="id";
	     user['req_master2']="id";
	     if(data[a].mast==1){
	    	 user['req_master1']="selected";
	     }else{
	    	 user['req_master2']="selected";
	     }
	     
	     user['req_type1']="id";
	     user['req_type2']="id";
	     user['req_type3']="id";
	     if(data[a].type=='number'){
	    	 user['req_type2']="selected";
	     }else if(data[a].type=='boolean'){
	    	 user['req_type3']="selected";
	     }else{
	    	 user['req_type1']="selected";
	     }
	     
	     jPut.users.append(user);
	  }
  }
 
  //把请求返回参数写入页面
  function return_param(){
	  // var jsondata = <?php echo json_encode($info['api_result_field']); ?>;
    var jsondata = $('._hidden_api_result_field').val();
	  if(jsondata=='' || jsondata==null){
		  var user1=Object();
	      user1['ret_name']='';
	      user1['ret_desc']='';
	      user1['ret_type']='string';
	      
	      user1['ret_type1']='selected';
	      user1['ret_type2']='id';
	      user1['ret_type3']='id';
		  jPut.users1.append(user1);
		  return;
	  }
	  
	  var data = JSON.parse(jsondata);
	  for(var a in data){
	     var user1=Object();
	     user1['ret_name']=data[a].name;
	     user1['ret_type']=data[a].type;
	     user1['ret_desc']=data[a].desc;
	     
	     user1['ret_type1']="id";
	     user1['ret_type2']="id";
	     user1['ret_type3']="id";
	     if(data[a].type=='number'){
	    	 user1['ret_type2']="selected";
	     }else if(data[a].type=='boolean'){
	    	 user1['ret_type3']="selected";
	     }else{
	    	 user1['ret_type1']="selected";
	     }
	     
	     jPut.users1.append(user1);
	  }
  }
  
  //把错误码写入页面
  function error_param(){
	  // var jsondata = <?php echo json_encode($info['api_error_codes']); ?>;
    var jsondata = $('._hidden_api_error_codes').val();
	  if(jsondata=='' || jsondata==null){
		  var user2=Object();
	      user2['error_code']='';
	      user2['error_info']='';
	      user2['error_desc']='';
		  jPut.users2.append(user2);
		  return;
	  }
	  
	  var data = JSON.parse(jsondata);
	  for(var a in data){
	     var user2=Object();
	     user2['error_code']=data[a].code;
	     user2['error_info']=data[a].info;
	     user2['error_desc']=data[a].desc;
	     jPut.users2.append(user2);
	  }
  } 
  
  $(function (){
	  $(document)
	    .on('click','._request_param_del',function (){
	    	var that = $(this);
	    	that.parent().parent('._raw_request_param').remove();
	    }) 

		.on('click','._return_param_del',function (){
			var that = $(this);
		    that.parent().parent('._raw_return_param').remove();
	   }) 
	 
		.on('click','._error_param_del',function (){
	    	var that = $(this);
		    that.parent().parent('._raw_error_param').remove();
	 }) 		   
}); 
  
function getApiData(){
  var service_id = $('._service_id').val();
  var service_name_en = $('._service_name_en').val();
  var service_name = $('._service_name').val();
  var api_name = $('._api_name').val();
  var api_name_en = $('._api_name_en').val();
  var api_introduction = $('._api_introduction').val();
  //var api_timeout = $('._api_timeout').val();
  //请求方式
  var api_request_method = $("input[name='api_request_method']:checked").val()
  var api_result_format = $("._api_result_format").val();
  var api_authorized_type = $("._api_authorized_type").val();
  var api_uri = $('._api_uri').val();
  //var api_sample_url = $("._api_sample_url").val();

  var api_request_param = JSON.parse(getApiRequestParam("api_request_param",['name','type','mast','default_value','desc'],5) );
  // console.log(api_request_param);//return;
   var param_str = getParam(api_request_param);
   var api_sample_url = "http://{$info.service_host}/"+api_uri+"?"+param_str;

  var api_result_field = JSON.parse( getApiRequestParam("api_result_field",['name','type','desc'],3) );
  var result_field_str = getResultField(api_result_field);
  
  var api_error_codes = JSON.parse( getApiRequestParam("api_error_codes",['code','info','desc'],3) );
  var api_result_sample = $("._api_result_sample").val();
  var api_other_platform_sample = $("._api_other_platform_sample").val();
  var api_update_type = $("input[name='api_update_type']:checked").val()
  // var api_is_charge = $('._api_is_charge').val();
  var api_is_charge = $("input[name='api_is_charge']:checked").val();

  //参数为空判断
  batchVer('_blur_rz');
  
 //有错误样式不允许提交
 if (haserror('_blur_rz')) {
	return false;
 }
 //请求参数判断
 if(param_str=='no'){
	  return false;
 }
 //请求参数判断
 if(result_field_str=='no'){
	  return false;
 }

  //api提交
  var data = {};
  data.service_id = service_id;
  data.api_id = $('._api_id').val();
  data.api_name = api_name;
  data.service_name_en = service_name_en;
  data.service_name = service_name;
  data.api_name_en = api_name_en;
  data.api_introduction = api_introduction;
  //data.api_timeout = api_timeout;
  data.api_request_method = api_request_method;
  data.api_result_format = api_result_format;      
  data.api_authorized_type = api_authorized_type;      
  data.api_uri = api_uri;
  data.api_sample_url = api_sample_url;      
  data.api_request_param = api_request_param;
  data.api_result_field = api_result_field;      
  data.api_error_codes = api_error_codes;      
  data.api_result_sample = api_result_sample;
  data.api_other_platform_sample = api_other_platform_sample;      
  data.api_update_type = api_update_type;
  data.api_is_charge = api_is_charge;

  return data;

}

//拼装请求样例
function getParam(datajson){
  
  var param_string="";
  var rsv = true;
  for(var k in datajson){
    if(!stringIsNull($.trim(datajson[k].name)) && !checkEnName(datajson[k].name)){
      rsv=false;
    }
    param_string += "&"+ datajson[k].name+"="+datajson[k].default_value;
  }
  if(!rsv){
    return 'no';
  }
  param_string = param_string.substr(1);
  param_string = param_string.replace(' ','');
  return param_string;
}

function getResultField(datajson){
	var rsv = true;
	for(var k in datajson){
		if(!stringIsNull($.trim(datajson[k].name)) && !checkEnName(datajson[k].name)){
			rsv=false;
			//return false;
		}
	}
	if(!rsv){
		return 'no';
	}
	return 'yes';
}

//获取二维数组值及转json数据格式
function getApiRequestParam(dom_name,params,params_num){
    var api_request_param = $("input[name^='"+dom_name+"']");
    //console.log(api_request_param);
    var json_params = new Array();

    var array_num = Math.floor(api_request_param.length/params_num);
    for(var j=0;j<array_num;j++){
        //json_params[j] = new Array();
        json_params[j] = new Object();
    }

    for(var i=0;i<api_request_param.length;i++){
        var num = i%params_num;
        var key = Math.floor(i/params_num);
        json_params[key][params[num]] = api_request_param[i].value;
    }
    //console.log(json_params);
    //console.log(JSON.stringify(json_params));return false;
    return JSON.stringify(json_params);
}

// 获取option值
function selectChange(obj,classname,val){
  var val  = $(obj).val();
  $(obj).next('input[name=\''+classname+'\']').val(val);
}
